package com.qfedu.controller;

import com.qfedu.dto.BookDto;
import com.qfedu.dto.Page;
import com.qfedu.dto.Result;
import com.qfedu.entity.Book;
import com.qfedu.entity.Category;
import com.qfedu.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@CrossOrigin
@Controller
public class BookController {

    @Autowired
    private BookService bookService;

    /**
     * 添加图书接口
     */
    @ResponseBody
    @RequestMapping("/addBook")
    public Result addBook(@RequestBody BookDto bookDto){
        Result result = new Result();
        result.setCode(200);
        result.setMsg("success");
        Book book = new Book();
        book.setBookName(bookDto.getBookName());
        book.setAuthorName(bookDto.getAuthorName());
        book.setPrice(bookDto.getPrice());
        Category category = new Category();
        category.setCategoryId(bookDto.getCategoryId());
        book.setCategory(category);
        bookService.addBook(book);
        return result;
    }

    /**
     * 删除图书接口
     */
    @ResponseBody
    @RequestMapping("/deleteBook")
    public Result deleteBook(Integer bookId){
        Result result = new Result();
        result.setCode(200);
        result.setMsg("success");
        bookService.deleteBook(bookId);
        return result;
    }

    /**
     * 更新图书接口
     */
    @ResponseBody
    @RequestMapping("/updateBook")
    public Result updateBook(@RequestBody BookDto bookDto){
        Result result = new Result();
        result.setCode(200);
        result.setMsg("success");
        Book book = new Book();
        book.setBookId(bookDto.getBookId());
        book.setBookName(bookDto.getBookName());
        book.setAuthorName(bookDto.getAuthorName());
        book.setPrice(bookDto.getPrice());
        Category category = new Category();
        category.setCategoryId(bookDto.getCategoryId());
        book.setCategory(category);
        bookService.updateBook(book);
        return result;
    }

    /**
     * 分页图书接口
     */
    @ResponseBody
    @RequestMapping("/getBookPage")
    public Page getBookPage(int pageNo,int pageSize){
        Page page = bookService.getBookPage(pageNo, pageSize);
        return page;
    }


    @ResponseBody
    @RequestMapping("/getBookByBookId")
    public Result getBookByBookId(Integer bookId){
        Result result = new Result();
        result.setCode(200);
        result.setMsg("success");
        Book book = bookService.getBooKByBookId(bookId);
        result.setObj(book);
        return result;
    }
}
